package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.R;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/home/index")
public class HomeIndexController {
    @Autowired
    private IYddUserService yddUserService;

    /**
     * 前台登录
     * @param yddUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody YddUser yddUser){
        log.info("用户信息:{}",yddUser);
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile, yddUser.getMobile());
        YddUser yddUser1 = yddUserService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(yddUser1)){
            throw new NullPointerException("用户不存在");
        }
        String possword = DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes());
        log.info("密码为:{}",possword);
        if (!yddUser1.getPassword().equals(possword)){
            throw new BusinessException("用户密码错误");
        }

        Map tokenMap = new HashMap();
        tokenMap.put("id",yddUser1.getId());
        String token = JwtUtils.getToken(tokenMap);
        HashMap<String,String>map = new HashMap<>();
        map.put("token",token);
        return R.success("token",token);
    }
}
